package com.yang.common.util;

import com.yang.common.exception.CommonException;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * 命令行指令工具
 *
 * @author: yangjianzhi
 * @version1.0
 */
@Slf4j
public class CommonCommandUtil {

    /**
     * 还原数据库
     */
    public static void restoreDb(String host, String port, String dbName, String username, String password, String backupPath) throws IOException, InterruptedException {
        // 构建恢复命令
        String command = String.format(
                "mysql -u %s -p%s %s < %s",
                username, password, dbName, backupPath);

        // 执行恢复命令
        String[] c = { "/bin/bash", "-c", command };
        Process process = Runtime.getRuntime().exec(c);
        int exitCode = process.waitFor();
        if (exitCode == 0) {
            log.info("数据库还原成功");
        } else {
            log.error("数据库还原失败，exit code : " + exitCode);
            log.error("command : " + command);
            throw new CommonException("");
        }
    }

    /**
     * 备份数据库
     *
     * @return
     */
    public static void backupDb(String host, String port, String username, String password, String dbName, String backupPath) throws IOException, InterruptedException {
        String command = String.format(
                "mysqldump -u %s -p%s %s -r %s",
                username, password, dbName, backupPath);
        // 执行备份命令
        Process process = Runtime.getRuntime().exec(command);
        int exitCode = process.waitFor();
        if (exitCode == 0) {
            log.info("数据库备份完成成功");
        } else {
            log.error("数据库备份失败，exit code : " + exitCode);
            log.error("command : " + command);
            throw new CommonException("");
        }
    }
}
